package com.mall.mall.seckill.interceptor;

import com.mall.common.Vo.MemberResponseVo;
import com.mall.common.constant.AuthServerConstant;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginUserIntercepter implements HandlerInterceptor {
    public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/kill", requestURI);
        if (match){
            HttpSession session = request.getSession();
            MemberResponseVo user = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
            // 登陆过就放行
            if (null != user) {
                loginUser.set(user);
                return true;
            }
            // 否则，跳转到登录页面
            response.sendRedirect("http://auth.wtmall.com/login.html");
            return false;
        }

        return true;
    }
}
